package com.ruoyi.act.module.controller.modeler;

import com.github.pagehelper.PageInfo;
import com.ruoyi.act.module.domain.ActModel;
import com.ruoyi.act.module.service.IModelService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import org.activiti.engine.repository.Model;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 创建模型方法
 * @author hcj
 */
@RestController
@RequestMapping("/act/model")
public class ModelController extends BaseController {

    @Autowired
    private IModelService iModelService;

    private final static String suffix = ".bpmn";

    /**
     * 创建一个模型实例
     *
     * @param actModel
     * @return
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ActModel actModel) {
        Model model = iModelService.saveModel(actModel);
        return AjaxResult.success(model);
    }

    /**
     * 查询模型实例列表
     *
     * @param actModel
     * @return
     */
    @PostMapping("/list")
    public PageInfo<Model> findPage(@RequestBody ActModel actModel) {
        PageInfo<Model> pageInfo = iModelService.findPge(actModel);
        return pageInfo;
    }

    /**
     * 下载模型文件 xml
     *
     * @param modelId
     * @param response
     * @throws IOException
     */
    @GetMapping("/down/{modelId}")
    public void down(@PathVariable String modelId, HttpServletResponse response) throws IOException {
        ByteArrayInputStream byteArrayInputStream =iModelService.getModelEditorSource(modelId,response);
        String fileName = new SimpleDateFormat("yyyyMMddHHmmsss").format(new Date()) + suffix;
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        IOUtils.copy(byteArrayInputStream, response.getOutputStream());
        response.flushBuffer();
    }

    /**
     * 删除流程模型
     *
     * @param modelId
     */
    @GetMapping("/delete/{modelId}")
    public void delete(@PathVariable String modelId) {
        iModelService.deleteModel(modelId);
    }
}
